var scenerys = [],
    time = 0,   // 记录时间
    touchSlide = false, // 记录是否滑动
    scoreColor = 'red',
    scoreText = '+10',
    speed = 600,
    frequency = 40,
    ani = null,
    s = 0,
    ms = 99,
    ctx_s = '', ctx_ms = '',
    x1, x2, // 记录人物移动的初始X轴坐标和终点X轴坐标
    scenery, prop, draw, sceneryImage, isFirst,
    itemsImageData = [
        {
            x: 0,   // 所在图片的X轴位置
            y: 0,   // 所在图片的Y轴位置
            w: 120, // 所在图片的宽度
            h: 140, // 所在图片的高度
            ix: 0.45,   // 展示在屏幕上的初始X轴坐标
            iy: 0.3,    // 展示在屏幕上的初始Y轴坐标
            dx: 0.42,   // 手动设置的终点距起始点X轴坐标值差
            dy: 1.1 // 手动设置的终点距起始点Y轴坐标值差
        },{
            x: 0,
            y: 140,
            w: 120,
            h: 140,
            ix: 0.49,
            iy: 0.3,
            dx: 0.08,
            dy: 1.1
        },{
            x: 0,
            y: 280,
            w: 120,
            h: 80,
            ix: 0.535,
            iy: 0.3,
            dx: -0.23,
            dy: 1.1
        }
    ],
    figureImageData = [
        {
            w: 40,
            h: 65
        }
    ],
    plantImageData = [
        {
            x: 0.35,
            y: 0.23,
            dx: 0.5,
            dy: 0.57
        },{
            x: 0.59,
            y: 0.23,
            dx: -0.3,
            dy: 0.57
        }
    ],
    
    // 触摸事件变量
    startx,starty,movex,movey,endx,endy,nx,ny,angle;
var Width = document.documentElement.clientWidth,   // 获取设备宽度
    Height = document.documentElement.clientHeight, // 获取设备高度
    canvas = document.getElementById('canvas'),
    canvasPro = document.getElementById('progress'),
    back = document.getElementById('back'),
    ctxPro = canvasPro.getContext('2d'),
    ctx = canvas.getContext('2d'),
    intervalId; // 人物定时器
// 定义canvas高宽与设备高宽一致
canvasPro.width = Width;
canvasPro.height = Height;
canvas.width = Width;
canvas.height = Height;
back.width = Width;
back.height = Height;
function animate() {
    ctxPro.clearRect(0, 0, Width, Height);  // 清空画布
    // 两边植物
    if(time%frequency === 0){
        scenery.initial();
    }
    for(let i = pantArrLength; i < scenery.arr.length; i ++) {
        ctxPro.globalCompositeOperation = 'destination-over';
        // 左边植物绘制
        ctxPro.drawImage(scenery.arr[i].imgLeft, 0, 0, scenery.arr[i].oriW, scenery.arr[i].oriH, scenery.arr[i].lx, scenery.arr[i].ly, scenery.arr[i].w, scenery.arr[i].h);
        // 右边植物绘制
        ctxPro.drawImage(scenery.arr[i].imgRight, 0, 0, scenery.arr[i].oriW, scenery.arr[i].oriH, scenery.arr[i].rx, scenery.arr[i].ry, scenery.arr[i].w, scenery.arr[i].h);
        // 轨道
        scenery.progress(i);
    }
    if(time%frequency === 0) {
        prop.initial();
    }
    for(let i = arrLength; i < prop.arr.length; i ++) {
        var propXC = prop.arr[i].px + prop.arr[i].pw / 2;
        var drawXC = draw.locationX + draw.mainImgWidth / 2;
        var propYC = prop.arr[i].py + prop.arr[i].ph / 2;
        var drawYC = draw.locationY + draw.mainImgHeight / 2;
        // 道具与人物碰撞检测
        if(Math.abs(propXC - drawXC) < (Width / 10) && Math.abs(propYC - drawYC) < (Width / 10)) {
            if(prop.arr[i].propImageNum === 0) {
                draw.num += 50;
                draw.drawScore('+50', 'yellow', draw.locationX + Width / 11);
            }else if(prop.arr[i].propImageNum === 1) {
                draw.num += 10;
                draw.drawScore('+10', 'yellow', draw.locationX + Width / 11);
            }else if(prop.arr[i].propImageNum === 2) {
                draw.num -= 200;
                draw.drawScore('-200', 'red', draw.locationX + Width / 11);
            }
            // 删除被碰撞的数组，并让循环起始下标值+1
            delete prop.arr[arrLength];
            arrLength ++;
        }else if(prop.arr[i].py > Height) {
        	// 删除超出边界数组，并让循环起始下标值+1
            delete prop.arr[arrLength];
            arrLength ++;
        }else{
            ctxPro.drawImage(prop.arr[i].propImage, prop.arr[i].propSx, prop.arr[i].propSy, prop.arr[i].propImageW, prop.arr[i].propImageH, prop.arr[i].px, prop.arr[i].py, prop.arr[i].pw, prop.arr[i].ph);
            // 轨道
            prop.progress(i);
        }
    }
    
    if(time%6 === 0) {
        draw.progress();
    }
    // 在没绘制一张小图片之前,都要清空之前绘制的图片,这样才能显示出动画效果来,
    ctx.clearRect(0, 0, Width, Height);
    ctx.fillStyle = '#333';
    ctx.font = '1rem 黑体';
    ctx.fillText('分数：' + draw.num, Width / 20, Width / 10);
    ctx.fillStyle = draw.scoreColor;
    ctx.font = '1rem 黑体';
    ctx.fillText(draw.scoreText, draw.scoreTextX, draw.scoreTextY);
    draw.score();
    ctx.fillStyle = '#e78a21';
    ctx_s = s;
    ctx_ms = ms;
    ctx_s<10&&(ctx_s = '0' + ctx_s);
    ctx_ms<10&&(ctx_ms = '0' + ctx_ms);
    ctx.fillText('倒计时：' + ctx_s + '：' + ctx_ms, Width/3, Width/10);
    //  在大图上剪切绘制绘制
    ctx.drawImage(draw.personImg, draw.columnIndex * draw.singleWidth, draw.inx * draw.singleHeight, draw.singleWidth, draw.singleHeight, draw.locationX, draw.locationY, draw.mainImgWidth, draw.mainImgHeight);
    if(touchSlide) {
        draw.slide(x1 , x2);
    }
    time ++;
    if(s === 0 && ms === 0) {
        document.getElementsByClassName('results-text')[0].innerHTML = `你的成绩为：${draw.num}分`;
        document.getElementsByClassName('game-over')[0].style.display = 'block';
        cancelAnimationFrame(animate);
    }else{
    	requestAnimationFrame(animate);
    }
    
}
const Draw = function (direction) {
    this.num = 0;
    this.figureNum = 0;
    this.singleWidth = figureImageData[0].w;  // 每一个小图片的宽度
    this.singleHeight = figureImageData[0].h;  // 每一个小图片的高度
    this.mainImgWidth = Width / 4;  // 人物展示的实际宽度
    this.mainImgHeight = (this.mainImgWidth / this.singleWidth) * this.singleHeight;
    this.x = (Width / 2) - (this.mainImgWidth / 2);
    this.initial(direction, this.x, 2);
    this.scoreTextY = this.locationY + 5;
}
Draw.prototype = {
    initial: function(direction, x, index) {
        this.figureIndex = index;
        this.figureImageX = x;
        this.figureImageY = this.mainImgHeight * 2.7;
        this.inx = direction;  // 当前是第几行的图片
        this.personImg = img[0];    // 人物图
        this.columnIndex = 0; // 当前是第几列的图片
        this.frames = 10;  // 一秒有几帧
        this.locationX = this.figureImageX; // 在X轴位置
        this.locationY = this.figureImageY; // 在Y轴位置
    },
    progress: function() {
        this.columnIndex += 1;
        this.columnIndex %= 4;
    },
    slide: function(x, x1) {
        this.Vfx = (x1 - x) / 8;
        if(x > x1) {
            if(this.locationX >= x1) {
                this.locationX += this.Vfx;
            }else{
                this.locationX = x1;
                touchSlide = false;
            }
        }else{
            if(this.locationX <= x1) {
                this.locationX += this.Vfx;
            }else{
                this.locationX = x1;
                touchSlide = false;
            }
        }
    },
    score: function() {
    	this.scoreTextY -= 0.5;
    	if(this.scoreTextY === (this.locationY - 40)) {
    		this.scoreText = '';
    		this.scoreTextY = this.locationY;
    	}
    },
    drawScore: function(t, c, x) {
        this.scoreText = t;
        this.scoreColor = c;
    	this.scoreTextX = x;
    	this.scoreTextY = this.locationY;
    }
}
const Scenery = function(w, h) {
    this.arr = [];
}
Scenery.prototype = {
    // 初始化
    // X轴、Y轴、宽度、高度的偏移量计算是根据手动设置的两点数量差得来的
    initial: function(k) {
        // 景物图片
        var plantArr = [];
        this.ww = Width *0.08;
        plantArr.imgLeft = img[progressImageRandom(2, 3, 0.5)];
        plantArr.imgRight = img[progressImageRandom(2, 3, 0.5)];
        // 两种植物图片宽高一致
        plantArr.oriW = img[2].naturalWidth; // 图片原始宽度
        plantArr.oriH = img[2].naturalHeight;    // 图片原始高度
        // 设定两个坐标，A(x1,y1)和B(x2,y2),根据这两个坐标来确立运动线的位置（要考虑物体大小变化）
        // A(Width * 0.35,Width * 0.23)和B(- Width * 0.15,Width * 0.23)
        // A为起始点，B为终点
        // 物体起始W1=this.w宽度和终点宽度W2=((Width / 4))
        plantArr.lx = Width * plantImageData[0].x;  // 左边植物初始X轴坐标
        plantArr.ly = Width * plantImageData[0].y;  // 左边植物初始Y轴坐标
        plantArr.rx = Width * plantImageData[1].x;  // 左边植物初始X轴坐标
        plantArr.ry = Width * plantImageData[1].y;  // 左边植物初始Y轴坐标
        plantArr.w = Width / 12; // 图片展示宽度
        plantArr.h = (this.ww /  plantArr.oriW) *  plantArr.oriH; // 图片展示高度
        plantArr.t = speed; // 起点到终点的时间（速度）
        this.plantH = (this.ww / plantArr.oriW) * plantArr.oriH; // 植物起点高度
        plantArr.ldx = plantImageData[0].dx * Width;
        plantArr.ldy = plantImageData[0].dy * Width;
        plantArr.rdx = plantImageData[1].dx * Width;
        plantArr.rdy = plantImageData[1].dy * Width;
        this.arr.push(plantArr);
    },
    progress: function(k) {
    	this.Vlx = this.arr[k].ldx / this.arr[k].t; // X轴偏移量
        this.Vly = this.arr[k].ldy / this.arr[k].t; // Y轴偏移量
    	this.Vrx = this.arr[k].rdx / this.arr[k].t; // X轴偏移量
        this.Vry = this.arr[k].rdy / this.arr[k].t; // Y轴偏移量
        this.Vw = ((Width / 4) - (Width / 12)) / this.arr[k].t; // 宽度偏移量
        this.Vh = ((((Width / 4) / (Width / 12)) * this.plantH) - this.plantH ) / this.arr[k].t; // 高度偏移量
        
        this.arr[k].lx -= this.Vlx; // 每秒X轴移动的位置
        this.arr[k].ly += this.Vly; // 每秒Y轴移动的位置
        this.arr[k].rx -= this.Vrx; // 每秒X轴移动的位置
        this.arr[k].ry += this.Vry; // 每秒Y轴移动的位置
        this.arr[k].w += this.Vw; // 每秒植物宽度的变化
        this.arr[k].h += this.Vh; // 每秒植物高度的变化
        this.arr[k].t -= 3; // 速度逐步加快
        // 当物体超出屏幕范围，初始化
        if(this.arr[k].ly  > Height) {
            delete this.arr[pantArrLength];
            pantArrLength ++;
        }
    }
}

const Prop = function () {
    this.arr = [];
}
Prop.prototype = {
    initial: function(k) {
        var propArr = [];
        this.propW = Width / 30;
        this.propLocationNum = randomNum(0, 2);
        propArr.t = speed; // 起点到终点的时间（速度）
        propArr.propImageNum = propRandom(0, 1, 2, 0.1, 0.7); // 给定概率出现的道具（石头、金币、宝箱）
        propArr.propImage = img[4]; // 道具
        propArr.propImageW = itemsImageData[propArr.propImageNum].w;
        propArr.propImageH = itemsImageData[propArr.propImageNum].h;
        propArr.propSx = itemsImageData[propArr.propImageNum].x;
        propArr.propSy = itemsImageData[propArr.propImageNum].y;
        propArr.px =  Width * itemsImageData[this.propLocationNum].ix;
        propArr.py =  Width * itemsImageData[this.propLocationNum].iy;
        propArr.dx =  Width * itemsImageData[this.propLocationNum].dx;
        propArr.dy =  Width * itemsImageData[this.propLocationNum].dy;
        propArr.pw = this.propW;
        propArr.ph = (this.propW / propArr.propImageW) * propArr.propImageH;
        propArr.propW = this.propW;
        propArr.propH = (this.propW / propArr.propImageW) * propArr.propImageH;
        this.arr.push(propArr);
    },
    progress: function(k) {
        this.Vpx = this.arr[k].dx / this.arr[k].t; // X轴偏移量
        this.Vpy = this.arr[k].dy / this.arr[k].t; // Y轴偏移量
        this.Vpw = ((Width / 5) - (Width / 30)) / this.arr[k].t; // 宽度偏移量
        this.Vph = ((((Width / 5) / (Width / 30)) * this.arr[k].propH) - this.arr[k].propH ) / this.arr[k].t; // 高度偏移量
        this.arr[k].px -= this.Vpx; // 每秒X轴移动的位置
        this.arr[k].py += this.Vpy; // 每秒Y轴移动的位置
        this.arr[k].pw += this.Vpw; // 每秒植物宽度的变化
        this.arr[k].ph += this.Vph; // 每秒植物高度的变化
        this.arr[k].t -= 3; // 速度逐步加快
    }
}
function progressImageRandom(a, b, n) {
    var random = Math.random();
    if (random < n) {
        return a;
    }else{
        return b;
    }
}
function propRandom(a, b, c, n, m) {
    var random = Math.random();
    if (random < n) {
        return a;
    }else if(random >= n && random < m){
        return b;
    }else{
        return c;
    }
}
function randomNum(minNum,maxNum){ 
    switch(arguments.length){ 
        case 1: 
            return parseInt(Math.random()*minNum+1,10); 
        break; 
        case 2: 
            return parseInt(Math.random()*(maxNum-minNum+1)+minNum,10); 
        break; 
            default: 
                return 0; 
            break; 
    } 
}
//开始触摸函数，event为触摸对象
function touchs(event){
    
    //阻止浏览器默认滚动事件
    event.preventDefault();
    
    //获取DOM标签
    var box = document.getElementById('progress');
    //通过if语句判断event.type执行了哪个触摸事件
    if(event.type=="touchstart"){
        // console.log('开始');
        isFirst = true;
         //获取开始的位置数组的第一个触摸位置
        var touch = event.touches[0];
         //获取第一个坐标的X轴
        startx = Math.floor(touch.pageX);
        //获取第一个坐标的X轴
        starty = Math.floor(touch.pageY);
        //触摸中的坐标获取
    }else if(event.type=="touchmove"){
    
        // console.log('滑动中');
        var touch = event.touches[0];
        movex = Math.floor(touch.pageX);
        movey = Math.floor(touch.pageY);
            //获取最后的坐标位置
        endx = Math.floor(event.changedTouches[0].pageX);
        endy = Math.floor(event.changedTouches[0].pageY);
         // console.log('结束');
         
         //获取开始位置和离开位置的距离
        nx = endx-startx;
        ny = endy-starty;
        
        //通过坐标计算角度公式 Math.atan2(y,x)*180/Math.PI
        angle = Math.atan2(ny, nx) * 180 / Math.PI;
        if(Math.abs(nx)<=1 ||Math.abs(ny)<=1){
            return false;
            // console.log('滑动距离太小');
        }
        if(angle<45 && angle>=-45) {
            if(isFirst) {
                // console.log(11111);
                if(draw.figureIndex === 1) {
                    draw.figureIndex += 1;
                    touchSlide = true;
                    x1 = draw.locationX;
                    x2 = (Width / 2) - (draw.mainImgWidth / 2);
                }else if(draw.figureIndex === 2) {
                    draw.figureIndex += 1;
                    touchSlide = true;
                    x1 = draw.locationX;
                    x2 = (Width / 1.25) - (draw.mainImgWidth / 2);
                }else if(draw.figureIndex === 3) {
                    draw.figureIndex = 3;
                }
                // console.log('右滑动','位置：' + draw.figureIndex);
            }
            isFirst = false;
        }else if((angle<=180 && angle>=135) || (angle>=-180 && angle<-135 )) {
            if(isFirst) {
                if(draw.figureIndex === 1) {
                    draw.figureIndex = 1;
                }else if(draw.figureIndex === 2) {
                    draw.figureIndex -= 1;
                    touchSlide = true;
                    x1 = draw.locationX;
                    x2 = (Width / 7) - (draw.mainImgWidth / 2);
                }else if(draw.figureIndex === 3) {
                    draw.figureIndex -= 1;
                    touchSlide = true;
                    x1 = draw.locationX;
                    x2 = (Width / 2) - (draw.mainImgWidth / 2);
                }
                // console.log('左滑动','位置：' + draw.figureIndex);
            }
            isFirst = false;
        }
        //当手指离开屏幕或系统取消触摸事件的时候
    }else if(event.type == "touchend" || event.type == "touchcancel"){
        
        //通过滑动的角度判断触摸的方向
        // if(angle<45 && angle>=-45){
            
        // }else if((angle<=180 && angle>=135) || (angle>=-180 && angle<-135 )){
            
        // }
        // else if(angle<=-45 && angle >=-135){
        //     console.log('上滑动');
        //     return false;
        // }else if(angle<135 && angle>=45){
        //     console.log('下滑动');
        //     return false;
        // }
    }
}

// 单纯分钟和秒倒计时
function resetTime(time){
    // console.log(111);
    // console.log('time', time);
    var timer=null;
    var t=time;
    s=Math.floor(t%60);
    function countDown(){
        ms--;
        if(ms<0){
            ms = 99;
            s --;
        }
        if(s===0 && ms===0) {
            clearInterval(timer);
        }
        // console.log(m+"分钟"+s+"秒"+ms);
    }
    timer=setInterval(countDown,10);
}
// 补丁
window.requestAnimationFrame = (function(){
    return  window.requestAnimationFrame       ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame    ||
            function( callback ){
                window.setTimeout(callback, 1000 / 60);
            };
})();